package com.mojo.jvm.gc_01_reference;

import com.mojo.jvm.jvm_01_javassit.Base;

import java.lang.ref.PhantomReference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

/**
 * 强引用、软引用、弱引用、虚引用实例
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class ReferenceDemo {
    public static void main(String[] args) {
        //strongReference();
        //softReference();
        weakReference();
        //phantomReference();
    }

    private static void phantomReference() {
        Base base = new Base();
        PhantomReference<Base> pf = new PhantomReference<>(base, null);
        base = null;
        //永远返回null
        System.out.println(pf.get());
        //返回是否从内存中已经删除
        System.out.println("是否被垃圾回收器标记 >>> " + pf.isEnqueued());

    }

    private static void weakReference() {
        Base base = new Base();
        WeakReference<Base> weakReference = new WeakReference<>(base);
        base = null;
        System.gc();
        System.out.println("弱引用 >>> " + weakReference.get());
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("是否被垃圾回收器标记 >>> " + weakReference.isEnqueued());
    }

    private static void softReference() {
        Base base = new Base();
        SoftReference<Base> softReference = new SoftReference<>(base);
        base = null;
        System.gc();
        System.out.println("软引用 >>> " + softReference.get());
        System.out.println("是否被垃圾回收器标记 >>> " + softReference.isEnqueued());
    }

    private static void strongReference() {
        Object o = new Object();
        System.out.println(">>> 强应用");
    }
}
